package com.quanxiaoha.xiaohashu.oss.biz.strategy.impl;

import com.quanxiaoha.xiaohashu.oss.biz.config.MinioConfig;
import com.quanxiaoha.xiaohashu.oss.biz.config.MinioProperties;
import com.quanxiaoha.xiaohashu.oss.biz.strategy.FileStrategy;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;


@Slf4j
public class MinioFileStrategy implements FileStrategy  {

    @Resource
    private MinioClient minioClient;
    @Resource
    private MinioProperties minioProperties;

    @Override
    @SneakyThrows
    public String uploadFile(MultipartFile file, String bucketName) {
        log.info("## 上传文件至 Minio ...");

        if(file == null || file.getSize() == 0) {
            log.error("==> 上传文件异常：文件大小为空 ...");
            throw new RuntimeException("文件大小不能为空");
        }
        // 原始名
        String originalFilename = file.getOriginalFilename();
        // Content-Type
        String contentType = file.getContentType();

        // 生成存储对象名称
        String key = UUID.randomUUID().toString().replace("-", "");
        // 获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = key + suffix;

        log.info("==> 开始上传文件至 Minio, ObjectName: {}", objectName);

        // 上传Minio
        minioClient.putObject(PutObjectArgs.builder()
                        .object(objectName)
                        .bucket("xiaohashu")
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(contentType)
                        .build());
        String url = minioProperties.getEndpoint() + "/" + bucketName + "/" + objectName;
        log.info("==> 上传文件至 Minio 成功，访问路径: {}", url);
        return url;
    }
}

